package com.movie.service.impl;

import com.movie.model.Screening;
import com.movie.model.Ticket;
import com.movie.service.MovieService;
import com.movie.service.UserService;
import com.movie.util.DataUtil;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

public class UserServiceImpl implements UserService {

    private DataUtil dataUtil;
    private MovieService movieService;

    public UserServiceImpl(DataUtil dataUtil, MovieService movieService) {
        this.dataUtil = dataUtil;
        this.movieService = movieService;
    }

    @Override
    public Ticket bookTicket(String screeningId, int seatNumber) {
        List<Ticket> tickets = dataUtil.loadTickets();
        Screening screening = movieService.getScreeningById(screeningId);

         if(screening.getSeatsAvailable() <= 0){
            return null;
        }
        screening.setSeatsAvailable(screening.getSeatsAvailable()-1);
        movieService.updateScreening(screening);
        String ticketId = UUID.randomUUID().toString();
        Ticket ticket = new Ticket(ticketId, screeningId, seatNumber);
         tickets.add(ticket);
        dataUtil.saveTickets(tickets);
        return  ticket;
    }

    @Override
    public List<Ticket> getMyTickets() {
       List<Ticket> tickets = dataUtil.loadTickets();
       return tickets;
    }

   @Override
   public void deleteTicket(String id) {
       List<Ticket> tickets = dataUtil.loadTickets();
       tickets.removeIf(ticket -> ticket.getId().equals(id));
        dataUtil.saveTickets(tickets);
   }
}